package com.wynn.controller;

import com.wynn.Exception.EmptyException;
import com.wynn.pojo.*;
import com.wynn.serviceFeign.PlanClient;
import com.wynn.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@RestController
@RequestMapping("plan")
@Slf4j
public class PlanController {

    @Autowired
    private PlanClient planClient;

    //获取首页第一副统计图的数据
    @GetMapping("ChartData1")
    Result getchartData1(){
        return planClient.getChartData1();
    }

    //加载生产任务
    @GetMapping("selectAll")
    Result selectAll(){
        Result result = new Result();
        try {
            List<PlanSummary> planSummaries = planClient.selectAll();
            result.setData(planSummaries);
            result.setCode("200");
        }catch (Exception e)
        {
            log.warn("生产任务加载失败");
            result.setCode("503");
            result.setMessage("生产任务加载失败");
            e.printStackTrace();
        }
        return result;
    }

    //添加生产任务
    @PostMapping("addPlan")
    @PreAuthorize("hasRole('planning') || hasRole('admin')")
    Result addPlan(@RequestBody PlanSummary planSummary){
        Result result = new Result();
        try{
            planClient.addPlan(planSummary);
            result.setCode("200");
            result.setMessage("添加成功");
        }catch (Exception e){
            log.warn("生产任务添加失败");
            result.setCode("503");
            result.setMessage("添加失败");
            e.printStackTrace();
        }
        return result;
    }

    //修改生产任务
    @PostMapping("editPlan")
    @PreAuthorize("hasRole('planning') || hasRole('admin')")
    Result editPlan(@RequestBody PlanSummary planSummary){
        Result result = new Result();
        try{
            planClient.editPlan(planSummary);
            result.setCode("200");
            result.setMessage("修改成功");
        }catch (Exception e){
            log.warn("生产任务修改失败");
            result.setCode("503");
            result.setMessage("修改失败");
            e.printStackTrace();
        }
        return result;
    }

    //删除生产任务
    @PostMapping("deletePlan")
    @PreAuthorize("hasRole('planning') || hasRole('admin')")
    Result deletePlan(@RequestBody PlanSummary planSummary){
        Result result = new Result();
        try{
            planClient.deletePlan(planSummary);
            result.setCode("200");
            result.setMessage("删除成功");
        }catch (Exception e){
            log.warn("生产任务删除失败");
            result.setCode("503");
            result.setMessage("删除失败");
            e.printStackTrace();
        }
        return result;
    }

    // 条件查询(按日查询)
    @PostMapping("search")
    Result search(@RequestBody SearchPlan searchPlan){
        Result result = new Result();
        try{
            List<PlanSummary> planSummaries = planClient.search(searchPlan.getProductLine(),searchPlan.getProduceDate());
            result.setCode("200");
            result.setData(planSummaries);
            result.setMessage("查询成功");
        }catch (Exception e){
            log.warn("生产任务搜索失败");
            result.setCode("503");
            result.setMessage("查询失败");
        }

        return result;
    }


    // 条件查询(按日查询)
    @PostMapping("searchOnePlan")
    Result searchOnePlan(@RequestBody SearchPlan searchPlan){
        Result result = new Result();
        try{
            List<PlanSummary> planSummaries = planClient.searchOnePlan(searchPlan.getProductLine(),searchPlan.getProduceDate());
            if(planSummaries.size()==0){
                throw new EmptyException("当日无生产任务");
            }
            result.setCode("200");
            result.setData(planSummaries);
            result.setMessage("查询成功");
        }catch (EmptyException e){
            result.setMessage(e.getMessage());
            result.setCode("504");
        }catch (Exception e){
            log.warn("生产人俗搜索失败");
            result.setCode("503");
            result.setMessage("查询失败");
        }

        return result;
    }

    //导入生产计划（按月导入)
    @PostMapping("updatePlan")
    @PreAuthorize("hasRole('planning') || hasRole('admin')")
    void updatePlan(MultipartFile file, Date produceDate)throws Exception{

        ArrayList<ArrayList<String>> row = new ArrayList<>();
        InputStream in = null;
        try {
            //获取输入流
            in = file.getInputStream();
            Workbook workbook = new XSSFWorkbook(in);
            //获取第一张工作表
            Sheet sheet = workbook.getSheetAt(0);

            for (int i = 0; i < sheet.getPhysicalNumberOfRows(); i++) {
                //循环获取工作表的每一行
                Row sheetRow = sheet.getRow(i);
                //循环获取每一列
                ArrayList<String> cell = new ArrayList<>();
                for (int j = 0; j < sheetRow.getPhysicalNumberOfCells(); j++) {   //
                    //将每一个单元格的值装入列集合
                    sheetRow.getCell(j).setCellType(Cell.CELL_TYPE_STRING);
                    cell.add(sheetRow.getCell(j).getStringCellValue());
                }
                //将装有每一列的集合装入大集合
                row.add(cell);
            }
            planClient.importPlan(row,produceDate);
            log.info("导出生产任务");
        } catch (FileNotFoundException e) {
            log.warn("生产任务导出失败");
            e.printStackTrace();
            throw new Exception();
        } catch (IOException e) {
            log.warn("生产任务导出失败");
            e.printStackTrace();
            throw new Exception();
        }finally {
            //关闭资源
            if (in != null) {
                in.close();
            }
        }
    }

    //获取生产调度
    @PostMapping("scheduling")
    Result scheduling(@RequestBody SearchPlan searchPlan){

        Result result = new Result();
        try{
            //判断是否属于正在状态
            CalcuStatue calcuStatue = planClient.calcuStatue(searchPlan);
            if(calcuStatue!=null ){
                result.setCode("505");
                result.setMessage("该生产计划在正在计算中,请等待");
                return result;
            }
            //当日生产顺序
            Schedule schedule = planClient.schedule(searchPlan.getProduceDate(),searchPlan.getProductLine());
            if(schedule==null){
                log.warn("生产任务未排产");
                throw new EmptyException("该投产顺序仍未计算，请点击计算");
            }

            result.setCode("200");
            result.setData(schedule);
            result.setMessage("查询成功");
        }catch (EmptyException e){
            log.warn("查询生产调度失败");
            result.setCode("504");
            result.setMessage(e.getMessage());
        }catch (Exception e){
            log.warn("查询生产调度失败");
            result.setCode("503");
            result.setMessage("查询失败");
        }
        return result;
    }

    @PostMapping("calculation")
    @PreAuthorize("hasRole('planning') || hasRole('admin')")
    Result calculation(@RequestBody PlanSummary planSummary){
        Result result = new Result();
        try{
            planClient.calculation(planSummary);
            result.setCode("200");
            result.setMessage("该生产计划在正在计算中,请等待");
            log.info("计算生产任务");
        }catch (Exception e){
            log.warn("计算生产调度失败");
            result.setCode("503");
            result.setMessage("计算失败");
        }
        return result;
    }


}
